import subprocess
import sys
import os
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler('install.log', encoding='utf-8')
    ]
)
logger = logging.getLogger("Dependencies-Installation")

def install_requirements():
    """安装项目依赖"""
    try:
        # 安装主要依赖
        requirements_file = "requirements.txt"
        if os.path.exists(requirements_file):
            logger.info("正在安装主要依赖...")
            subprocess.check_call([
                sys.executable, "-m", "pip", "install", "-r", requirements_file
            ])
        
        # 安装后端特定依赖
        backend_requirements = "backend/requirements.txt"
        if os.path.exists(backend_requirements):
            logger.info("正在安装后端依赖...")
            subprocess.check_call([
                sys.executable, "-m", "pip", "install", "-r", backend_requirements
            ])
            
        # 确保安装了必要的包
        essential_packages = [
            "fastapi", "uvicorn", "pyjwt", "python-multipart", 
            "psutil", "pydantic", "pillow"
        ]
        
        logger.info("正在安装核心包...")
        subprocess.check_call([
            sys.executable, "-m", "pip", "install", *essential_packages
        ])
        
        logger.info("所有依赖安装完成")
        return True
        
    except Exception as e:
        logger.error(f"安装依赖时出错: {str(e)}")
        return False

if __name__ == "__main__":
    logger.info("开始安装项目依赖...")
    success = install_requirements()
    
    if success:
        logger.info("依赖安装成功，您现在可以运行项目了")
    else:
        logger.error("依赖安装过程中出现错误，请查看日志获取详细信息")
        sys.exit(1) 